package sysinit

import (
	"IrisJwtCasbin/config"
	redigo "github.com/gomodule/redigo/redis"
	"time"
)

type Redis struct {
	pool *redigo.Pool
}

var redis *Redis

func init() {
	redis = new(Redis)
	redis.pool = &redigo.Pool{
		MaxIdle:     config.Config.REDIS.MaxIdle,
		MaxActive:   config.Config.REDIS.MaxActive,
		IdleTimeout: time.Duration(config.Config.REDIS.IdleTimeout),
		Dial: func() (redigo.Conn, error) {
			return redigo.Dial(
				config.Config.REDIS.Network,
				config.Config.REDIS.Addr,
				redigo.DialReadTimeout(time.Duration(config.Config.REDIS.Timeout)*time.Millisecond),
				redigo.DialWriteTimeout(time.Duration(config.Config.REDIS.Timeout)*time.Millisecond),
				redigo.DialConnectTimeout(time.Duration(config.Config.REDIS.Timeout)*time.Millisecond),
				redigo.DialDatabase(config.Config.REDIS.Database),
				redigo.DialPassword(config.Config.REDIS.Password),
			)
		},
	}
}

func RedisExec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
	con := redis.pool.Get()
	if err := con.Err(); err != nil {
		return nil, err
	}
	defer con.Close()
	parmas := make([]interface{}, 0)
	parmas = append(parmas, key)

	if len(args) > 0 {
		for _, v := range args {
			parmas = append(parmas, v)
		}
	}
	return con.Do(cmd, parmas...)
}

func RedisString(reply interface{}, err error) string {
	str, _ := redigo.String(reply, err)
	return str
}

func RedisStringMap(reply interface{}, err error) map[string]string {
	str, _ := redigo.StringMap(reply, err)
	return str
}

func RedisStrings(reply interface{}, err error) []string {
	str, _ := redigo.Strings(reply, err)
	return str
}
